<template>
  <div class="dsl-examples">
    <div class="header">
      <div class="header-content">
        <button class="back-button" @click="goToChat">
          <span class="back-icon">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
              <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
            </svg>
          </span>
          <span class="back-text">继续对话</span>
        </button>
        <div class="title-section">
          <h2>DSL 示例配置</h2>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>
    
    <div v-else-if="error" class="error-state">
      <i class="error-icon">⚠️</i>
      <span>{{ error }}</span>
    </div>
    
    <div v-else class="prompts-container">
      <ul v-if="dslExamples.length" class="prompt-list">
        <li v-for="(example, index) in dslExamples" 
            :key="index" 
            class="prompt-item"
            :class="{ 'editing': editingExample === example }">
          <div class="prompt-header">
            <h3>问题类型: {{ example.query_type }}</h3>
          </div>
          <div class="prompt-content">
            <pre v-if="!editingExample || editingExample.query_type !== example.query_type" 
                 @dblclick="startEdit(example)" 
                 :title="'双击编辑'"
                 class="prompt-text">{{ formatDslExample(example.dsl_example) }}</pre>
            <div v-else class="edit-area">
              <div class="edit-header">
                <span class="edit-title">正在编辑</span>
                <div class="edit-actions">
                  <button class="edit-btn save-btn" @click="saveEdit(example.query_type)">
                    <span class="btn-icon">✓</span>
                    保存
                  </button>
                  <button class="edit-btn cancel-btn" @click="cancelEdit">
                    <span class="btn-icon">✕</span>
                    取消
                  </button>
                </div>
              </div>
              <textarea 
                v-model="newDslExample"
                @keydown.esc="cancelEdit"
                class="edit-textarea"
                autofocus
              ></textarea>
              <div class="edit-footer">
                <div class="edit-tips">
                  <span class="tip-item">
                    <span class="tip-icon">⌘</span>
                    <span>ESC 取消</span>
                  </span>
                  <span class="tip-item">
                    <span class="tip-icon">⌘</span>
                    <span>Enter 换行</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <div v-else class="empty-state">暂无 DSL 示例</div>
    </div>
  </div>
</template>

<script>
import { API_BASE_URL } from '../config'
import { useRouter } from 'vue-router' // 导入 useRouter
import { ref } from 'vue'; // Import ref from Vue

export default {
  name: 'DslExamples',
  setup() {
    const router = useRouter(); // 创建 router 实例
    const goToChat = () => {
      router.push('/'); // 导航到主页（聊天界面）
    }

    // Use ref to create reactive properties
    const dslExamples = ref([]);
    const loading = ref(true);
    const error = ref(null);
    const editingExample = ref(null);
    const newDslExample = ref('');

    const fetchDslExamples = async () => {
      loading.value = true; // Set loading to true
      try {
        const response = await fetch(`${API_BASE_URL}/api/dsl-examples`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        dslExamples.value = data['dsl examples'] || []; // Update dslExamples
      } catch (err) {
        error.value = `获取 DSL 示例失败: ${err.message}`; // Update error
        console.error('Error fetching DSL examples:', err);
      } finally {
        loading.value = false; // Set loading to false
      }
    }

    fetchDslExamples(); // Call the function to fetch examples

    const cancelEdit = () => {
      editingExample.value = null; // Reset editing state
      newDslExample.value = ''; // Clear the new example value
    };

    return { 
      goToChat, 
      dslExamples, 
      loading, 
      error, 
      editingExample, 
      newDslExample, 
      fetchDslExamples,
      cancelEdit // Return the cancelEdit method
    };
  },
  methods: {
    formatDslExample(dsl) {
      try {
        // 尝试解析 DSL 示例
        const parsedDsl = JSON.parse(dsl);
        // 处理格式异常的 JSON
        if (typeof parsedDsl === 'object') {
          return JSON.stringify(parsedDsl, null, 2);
        } else {
          return dsl; // 返回原始字符串以避免崩溃
        }
      } catch (e) {
        console.error('Error parsing DSL example:', e);
        return dsl; // 返回原始字符串以避免崩溃
      }
    },
    startEdit(example) {
      this.editingExample = example;
      this.newDslExample = example.dsl_example;
    },
    async saveEdit(queryType) {
      if (this.newDslExample.trim()) {
        await this.updateDslExample(queryType, this.newDslExample);
      }
      this.editingExample = null;
    },
    async updateDslExample(queryType, newDslExample) {
      try {
        const response = await fetch(`${API_BASE_URL}/api/dsl-examples`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            query_type: queryType,
            dsl_example: newDslExample
          })
        });
        const result = await response.json();
        if (result.success) {
          await this.fetchDslExamples();
        } else {
          console.error('更新失败:', result.message);
        }
      } catch (error) {
        console.error('更新过程中发生错误:', error);
      }
    }
  }
}
</script>

<style scoped>
.dsl-examples {
  max-width: 1200px;
  min-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f2f5;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e3f2fd;
}

.back-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: #ffffff;
  color: #1976d2;
  border: 1px solid #e3f2fd;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(25, 118, 210, 0.05);
  height: 36px;
}

.back-button:hover {
  background-color: #1976d2;
  color: #ffffff;
  border-color: #1976d2;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(25, 118, 210, 0.15);
}

.prompts-container {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

.prompt-list {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.prompt-item {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  padding: 20px;
  transition: all 0.3s ease;
}

.prompt-item:hover {
  border-color: #90caf9;
  box-shadow: 0 2px 12px rgba(25, 118, 210, 0.1);
}

.prompt-item.editing {
  border-color: #1976d2;
  background: #fff;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}

.prompt-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.prompt-header h3 {
  margin: 0;
  color: #1976d2;
  font-size: 18px;
  font-weight: 500;
}

.prompt-text {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: inherit;
  line-height: 1.6;
  color: #2c3e50;
  cursor: pointer;
  padding: 12px;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.prompt-text:hover {
  background-color: #e3f2fd;
}

.edit-area {
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin: 8px 0;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
}

.edit-title {
  font-size: 14px;
  font-weight: 500;
  color: #64748b;
}

.edit-actions {
  display: flex;
  gap: 8px;
}

.edit-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.save-btn {
  background-color: #1976d2;
  color: white;
}

.save-btn:hover {
  background-color: #1565c0;
}

.cancel-btn {
  background-color: #f1f5f9;
  color: #64748b;
  border-color: #e2e8f0;
}

.cancel-btn:hover {
  background-color: #e2e8f0;
}

.edit-textarea {
  width: 100%;
  min-height: 150px;
  padding: 16px;
  border: none;
  background: #ffffff;
  color: #1e293b;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.6;
  resize: vertical;
}

.edit-textarea:focus {
  outline: none;
}

.edit-footer {
  padding: 8px 16px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

.edit-tips {
  display: flex;
  gap: 16px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #64748b;
}

.tip-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  background: #e2e8f0;
  border-radius: 3px;
  font-size: 10px;
  font-weight: 500;
}

.loading-state, .error-state, .empty-state {
  padding: 40px;
  text-align: center;
  color: #666;
  background: #f8fafc;
  border-radius: 8px;
  margin: 20px 0;
}

.loading-spinner {
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 3px solid #e3f2fd;
  border-radius: 50%;
  border-top-color: #1976d2;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.title-section {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.title-section h2 {
  margin: 0;
  color: #1976d2;
  font-size: 22px;
  font-weight: 600;
  letter-spacing: -0.5px;
}
</style>